package it.basketstats.testing;

import it.basketstats.R;
import it.basketstats.utility.DB.StatsDB;
import it.basketstats.utility.DB.TeamEntity;

import java.io.File;
import java.util.ArrayList;

import android.app.Activity;
import android.database.SQLException;
import android.os.Bundle;
import android.util.Log;

public class DBTestActivity extends Activity {

	private static final String TAG = "DBTest";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_dbtest);

		testDB();
	}

	private void testDB() {
		StatsDB db = new StatsDB(this);

		Log.i(TAG, "Starting Database test");

		Log.i(TAG, "checking database existence...");
		File dbFile = this.getDatabasePath("stats");
		if (dbFile.exists())
			Log.i(TAG, "...ok");
		else {
			Log.e(TAG, "ERROR!");
			return;
		}

		Log.i(TAG, "opening...");
		try {
			db.open();
		} catch (SQLException e) {
			Log.e(TAG, "ERROR!");
			return;
		}

		testTeam(db);
		
		db.close();
	}

	private void testTeam(StatsDB db) {
		TeamEntity team = new TeamEntity();
		ArrayList<TeamEntity> teams;

		Log.i(TAG, "adding new team...");
		try {
			db.teamAdd("test team");
		} catch (SQLException e) {
			Log.e(TAG, "ERROR!");
			return;
		}

		Log.i(TAG, "re-adding same team to test unicity...");
		try {
			db.teamAdd("test team");
		} catch (SQLException e) {
			Log.i(TAG, "...correctly not inserted");
		}

		Log.i(TAG, "retrive test team searching by name");
		team = db.teamSearchByName("test team");
		if (team != null)
			Log.i(TAG, team.toString());
		else {
			Log.e(TAG, "ERROR!");
			return;
		}

		Log.i(TAG, "retrive test team searching by id");
		team = db.teamSearchByID(team.getId());
		if (team != null)
			Log.i(TAG, team.toString());
		else {
			Log.e(TAG, "ERROR!");
			return;
		}

		Log.i(TAG, "retrive all team");
		teams = db.teamGetAll();
		if (teams != null)
			Log.i(TAG, teams.toString());
		else {
			Log.e(TAG, "ERROR!");
			return;
		}
		
		Log.i(TAG, "Deleting test team");
		try {
			db.teamDelete(team.getId());
		} catch (SQLException e) {
			Log.e(TAG, "ERROR!");
			return;
		}
		
		Log.i(TAG, "'teams' table tested");
	}

}
